<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 13-5-3
 * Time: 上午11:06
 * To change this template use File | Settings | File Templates.
 */

// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 统计操作类 marketingHandler
 * @package  htdocs
 * @subpackage  quanliadmin
 * create by allen.qiang
 * @version 1.0
 * =================================================================
 * @param $dbca                          DBCA
 * =================================================================
 * @abstract searchPermission()          查询权限信息
 * @abstract editPermission()            编辑、新增权限
 * @abstract getPermissionGroup()        获得所有的权限组
 * @abstract deletePermission()          删除权限信息
 * @abstract searchRoleGroup()           查询角色组信息
 * @abstract editRoleGroup()             编辑、新增角色组
 * @abstract searchRole()                查询角色信息
 * @abstract editRole()                  编辑、新增角色
 * @abstract searchRolePermission()      查询全部角色权限信息
 * @abstract editRolePermission()        分配角色权限信息
 * @abstract searchAllUser()             查询全部用户信息
 * @abstract getRoleAll()                获得全部角色信息并组装成二维数组
 * @abstract editUserRole()              新增、修改用户（含编辑用户角色）
 * @abstract changeUseFlg()              用户状态修改
 * @abstract deleteUser()                删除用户
 * =================================================================
 */
class marketingHandler {
	private $dbca;
	
	public function __construct( $dbca ) {
		$this->dbca = $dbca;
	}
	
	public function getFlowTable ($importData){
		$page = isset($importData['page']) ? trim($importData['page']) : '';//当前页
		$rp = isset($importData['rp']) ? trim($importData['rp']) : '';//每页记录数
		$sortname = isset($importData['sortname']) ? trim($importData['sortname']) : '';//排序字段名
		$sortorder = isset($importData['sortorder']) ? trim($importData['sortorder']) : '';//排序方式
		$startDate = isset($importData['startDate']) ? trim($importData['startDate']) : '';//开始时间
		$endDate = isset($importData['endDate']) ? trim($importData['endDate']) : '';//结束时间
		
		$sql_count = 'SELECT COUNT(vinfo.id) countNum FROM viewer_info vinfo';
		
		//统计时间段内每日的浏览次数（每日）
		$sql_pv_day = 'SELECT DATE_FORMAT(vinfo.createTime,"%Y-%m-%d") dataTime, COUNT(vinfo.id) countNum FROM viewer_info vinfo';
		
		//统计时间段内新独立IP浏览次数（每日）
		$sql_newInd_day = 'SELECT DATE_FORMAT(vinfo.createTime,"%Y-%m-%d") dataTime, COUNT(vinfo.id) countNum FROM viewer_info vinfo';
		
		//统计时间段内独立IP浏览次数（每日）
		$sql_ind_day = 'SELECT DATE_FORMAT(vinfo.createTime,"%Y-%m-%d") dataTime, COUNT(vinfo.id) countNum FROM viewer_info vinfo';
		
		//排序
		$str_order = '';
		
		//分页
		$str_limit = '';
		
		//查询条件
		$str_search = ' WHERE';
		
		//查询参数类型
		$type_search = '';
		
		$fromWay_str = ' AND vinfo.fromWay = 1';
		
		$son_str = ' AND vinfo.IP IN (SELECT vip.IP FROM viewer_IP vip 
					WHERE vip.createTime >= DATE_FORMAT(vinfo.createTime,"%Y-%m-%d 00:00:00") 
					AND vip.createTime <= DATE_FORMAT(vinfo.createTime,"%Y-%m-%d 23:59:59") )';
		
		$str_group = ' GROUP BY DATE_FORMAT(vinfo.createTime,"%Y-%m-%d")';
		
		//查询参数数组
		$param_search = array();
		
		if (!empty($startDate)){
			$str_search .= ' AND vinfo.createTime >= ?';
			$type_search .= 's';
			$param_search[] = $startDate.' 00:00:00';
		}
		
		if (!empty($endDate)){
			$str_search .= ' AND vinfo.createTime <= ?';
			$type_search .= 's';
			$param_search[] = $endDate.' 23:59:59';
		}
		
		//分页
		if (!empty($page) && !empty($rp)){
			$str_limit = sprintf(' LIMIT %d, %d', ($page - 1) * $rp, $rp);
		}
		
		//排序
		if (!empty($sortname) && !empty($sortorder)){
			$str_order = sprintf(' ORDER BY %s %s', $sortname, $sortorder);
		}
		
		//组装SQL语句
		if (!empty($type_search)){
			$str_search = str_replace('WHERE AND', 'WHERE', $str_search);
			$sql_count = $sql_count.$str_search.$str_group.$str_order;
			$sql_pv_day = $sql_pv_day.$str_search.$str_group.$str_order.$str_limit;
			$sql_newInd_day = $sql_newInd_day.$str_search.$fromWay_str.$son_str.$str_group.$str_order;
			$sql_ind_day = $sql_ind_day.$str_search.$fromWay_str.$str_group.$str_order;
		}else {
			$sql_count = $sql_count.$str_group.$str_order;
			$sql_pv_day = $sql_pv_day.$str_group.$str_order.$str_limit;
			$sql_newInd_day = $sql_newInd_day.$str_search.$fromWay_str.$son_str.$str_group.$str_order;
			$sql_newInd_day = str_replace('WHERE AND', 'WHERE', $sql_newInd_day);
			$sql_ind_day = $sql_ind_day.$str_search.$fromWay_str.$str_group.$str_order;
			$sql_ind_day = str_replace('WHERE AND', 'WHERE', $sql_ind_day);
		}
// 		error_log(print_r($sql_ind_day,true));
		if (!empty($type_search)){
			$result_count = $this->dbca->stmt_query($sql_count, $type_search, $param_search);
			$result_pv_day = $this->dbca->stmt_query($sql_pv_day, $type_search, $param_search);
			$result_newInd_day = $this->dbca->stmt_query($sql_newInd_day, $type_search, $param_search);
			$result_ind_day = $this->dbca->stmt_query($sql_ind_day, $type_search, $param_search);
		}else {
			$result_count = $this->dbca->stmt_query($sql_count);
			$result_pv_day = $this->dbca->stmt_query($sql_pv_day);
			$result_newInd_day = $this->dbca->stmt_query($sql_newInd_day);
			$result_ind_day = $this->dbca->stmt_query($sql_ind_day);
		}
		
		$flex_arr = array('count'=>0, 'data'=>array());
		
		if (!empty($result_count)){
			$flex_arr['count'] = count($result_count);
		}
		
		$day_arr = array();
		
		if (!empty($result_pv_day)) {
			foreach ($result_pv_day as $item){
				$flex_arr['data'][$item->dataTime]['day'] = $item->dataTime;
				$flex_arr['data'][$item->dataTime]['pv'] = $item->countNum;
				$flex_arr['data'][$item->dataTime]['ind'] = '';
				$flex_arr['data'][$item->dataTime]['newInd'] = '';
				$flex_arr['data'][$item->dataTime]['times'] = '';
				$flex_arr['data'][$item->dataTime]['percent'] = '';
				$day_arr[] = $item->dataTime;
			}
		}
		
		if (!empty($result_ind_day)){
			foreach ($result_ind_day as $item){
				if (in_array($item->dataTime, $day_arr)){
					$flex_arr['data'][$item->dataTime]['ind'] = $item->countNum;
					$flex_arr['data'][$item->dataTime]['times'] = sprintf("%.2f", ($flex_arr['data'][$item->dataTime]['pv'] / $item->countNum));
					$flex_arr['data'][$item->dataTime]['percent'] = round($item->countNum / $flex_arr['data'][$item->dataTime]['pv'] * 100, 2).'%';
				}
				
			}
		}
		
		if (!empty($result_newInd_day)){
			foreach ($result_newInd_day as $item){
				if (in_array($item->dataTime, $day_arr)){
					$flex_arr['data'][$item->dataTime]['newInd'] = $item->countNum;
				}
				
			}
		}
		
		return $flex_arr;
		
	}
	
	public function getFlowCharts ( $importData ){
		
		$startDate = isset($importData['startDate']) ? trim($importData['startDate']).' 00:00:00' : '';//开始时间
		$endDate = isset($importData['endDate']) ? trim($importData['endDate']).' 23:59:59' : '';//结束时间
		$countWay = isset($importData['countWay']) ? $importData['countWay'] : '';//统计方式（1：按PV、2：按独立访客、3：按新独立访客）
		
		//统计时间段内每日的浏览次数（每小时）
		$sql_pv_hour = 'SELECT DATE_FORMAT(createTime,"%H") dataTime, COUNT(id) countNum FROM viewer_info
					WHERE createTime >= ? AND createTime<= ? GROUP BY DATE_FORMAT(createTime,"%H")';
		
		//统计时间段内新独立IP浏览次数（每小时）
		$sql_newInd_hour = 'SELECT DATE_FORMAT(vinfo.createTime,"%H") dataTime, COUNT(vinfo.id) countNum FROM viewer_info vinfo
		
						WHERE vinfo.createTime >= ? AND vinfo.createTime<= ? AND vinfo.fromWay = 1
		
						AND vinfo.IP IN (SELECT vip.IP FROM viewer_IP vip WHERE vip.createTime >= DATE_FORMAT(vinfo.createTime,"%Y-%m-%d 00:00:00") AND vip.createTime <= DATE_FORMAT(vinfo.createTime,"%Y-%m-%d 23:59:59") )
		
						GROUP BY DATE_FORMAT(vinfo.createTime,"%H")';
		
		//统计时间段内独立IP浏览次数（每小时）
		$sql_ind_hour = 'SELECT DATE_FORMAT(createTime,"%H") dataTime, COUNT(id) countNum FROM viewer_info
					WHERE createTime >= ? AND createTime<= ? AND fromWay = 1
					GROUP BY DATE_FORMAT(createTime,"%H")';
		
		//按地区统计
		$sql_region = 'SELECT COUNT(id) countNum, region_id, region_name FROM viewer_info 
						WHERE createTime >= ? AND createTime<= ? GROUP BY region_id ORDER BY countNum DESC';
		//全部区域
		$sql_regionAll = 'select id, name from sys_region where region_level = 1';
		
		//来路域名统计
		$sql_from = 'SELECT COUNT(id) countNum, fromWay FROM viewer_info 
						WHERE createTime >= ? AND createTime<= ? GROUP BY fromWay';
		
		$result_pv = $this->dbca->stmt_query($sql_pv_hour, 'ss', array($startDate,$endDate));
		$result_ind = $this->dbca->stmt_query($sql_ind_hour, 'ss', array($startDate,$endDate));
		$result_newInd = $this->dbca->stmt_query($sql_newInd_hour, 'ss', array($startDate,$endDate));
		
		$result_region = $this->dbca->stmt_query($sql_region, 'ss', array($startDate,$endDate));
		$result_regionAll = $this->dbca->stmt_query($sql_regionAll);
		
		$result_from = $this->dbca->stmt_query($sql_from, 'ss', array($startDate,$endDate));
		
		$region_arr = array();
		$region_value = array();
		
		if (!empty($result_region)){
			foreach ($result_region as $region){
				$region_arr[] = $region->region_id;
				$region_value[$region->region_id] = $region->countNum;
			}
		}
		
		if (!empty($result_regionAll)){
// 			unset($result_regionAll[31]);
// 			unset($result_regionAll[33]);
			foreach ($result_regionAll as $region){
				
				if (in_array($region->id, $region_arr)){
// 					error_log(print_r($region->id,true));
					$region->value = $region_value[$region->id];
				}else {
					$region->value = 0;
				}
			}
		}
		
		$return_arr = array('coloum'	=> array('pv' => $result_pv, 'ind' => $result_ind, 'newInd' => $result_newInd),
							'region'	=> array('regionInfo' => $result_regionAll, 'valueMax' =>$result_region[0]->countNum),
							'from'		=> $result_from);
		
		return $return_arr;
	}
	
	/* 查询营销活动
	 * 失败return array('code' , 'message')
	 * 成功return array('code' , 'message'=>array('total', 'data'))
	 *  */
	public function searchMarketProject ($importData = array()){
		//返回数组
		$return_data = array();
		
		//错误信息
		$error = '';
		
		/* 传入数据有效性验证start */
		if (isset($importData['projectName']) && !is_string($importData['projectName'])){
			$error .= '活动名称必须为字符串<br/>';
		}
		
		if (isset($importData['groupID']) && !empty($importData['groupID']) && !is_numeric($importData['groupID'])){
			$error .= '活动分类必须为数字<br/>';
		}
		
		if (isset($importData['projectTime']) && !is_string($importData['projectTime'])){
			$error .= '活动时间必须为字符串<br/>';
		}
		
		if (isset($importData['projectID']) && !empty($importData['projectID']) && !is_numeric($importData['projectID'])){
			$error .= '活动ID必须为数字<br/>';
		}
		
		if (isset($importData['page']) && !empty($importData['page']) && !is_numeric($importData['page'])){
			$error .= '当前页码必须为数字<br/>';
		}
		
		if (isset($importData['rp']) && !empty($importData['rp']) && !is_numeric($importData['rp'])){
			$error .= '每页记录数必须为数字<br/>';
		}
		
		if (isset($importData['sortname']) && !empty($importData['sortname']) && !is_string($importData['sortname'])){
			$error .= '排序方式必须为字符串<br/>';
		}
		
		if (isset($importData['sortorder']) && !empty($importData['sortorder']) && !is_string($importData['sortorder'])){
			$error .= '排序方式必须为字符串<br/>';
		}
		 
		if (!empty($error)){
			$return_data['code'] = 400;
			$return_data['message']['total'] = 0;
			$return_data['message']['data'] = $error;
			return $return_data;
		}
		/* 传入数据有效性验证end */
		
		$projectName = isset($importData['projectName']) ? trim($importData['projectName']) : '';//活动名
		$projectID = isset($importData['projectID']) ? trim($importData['projectID']) : '';//活动ID
		$groupID = isset($importData['groupID']) ? trim($importData['groupID']) : '';//分类ID
		$projectTime = isset($importData['projectTime']) ? trim($importData['projectTime']) : '';//活动时间
		$page = isset($importData['page']) ? trim($importData['page']) : '';//当前页
		$rp = isset($importData['rp']) ? trim($importData['rp']) : '';//每页记录数
		$sortname = isset($importData['sortname']) ? trim($importData['sortname']) : '';//排序字段名
		$sortorder = isset($importData['sortorder']) ? trim($importData['sortorder']) : '';//排序方式
		$useFlg = isset($importData['useFlg']) ? trim($importData['useFlg']) : null;//启用状态
		
		//求总记录数
		$sql_count = 'SELECT COUNT(pd.projectID) countNum FROM project_detail pd';
		
		//查询SQL语句
		$sql_search = 'SELECT pd.*, pg.groupName, COUNT(pt.participateTimes) times FROM project_detail pd 
					   LEFT JOIN project_group pg ON pd.groupID = pg.groupID
					   LEFT JOIN project_times pt ON pd.projectID = pt.projectID';
		
		//排序
		$str_order = '';
		
		//分页
		$str_limit = '';
		
		//查询条件
		$str_search = ' WHERE';
		
		//查询参数类型
		$type_search = '';
		
		$str_group = ' GROUP BY pd.projectID';
		
		//查询参数数组
		$param_search = array();
		
		//查询条件：活动名
		if (!empty($projectName)){
			$str_search .= ' AND pd.projectName = ?';
			$type_search .= 's';
			$param_search[] = $projectName;
		}
		
		//查询条件：活动ID
		if (!empty($projectID)){
			$str_search .= ' AND pd.projectID = ?';
			$type_search .= 'i';
			$param_search[] = $projectID;
		}
		
		//查询条件：活动分类ID
		if (!empty($groupID)){
			$str_search .= ' AND pd.groupID = ?';
			$type_search .= 'i';
			$param_search[] = $groupID;
		}
		
		//查询条件：活动ID
		if (!empty($projectTime)){
			$str_search .= ' AND pd.startDate <= ? AND pd.endDate >= ?';
			$type_search .= 'ss';
			$param_search[] = $projectTime.' 00:00:00';
			$param_search[] = $projectTime.' 23:59:59';
		}
		
		//查询条件：启用状态
		if (!is_null($useFlg)){
			$str_search .= ' AND pd.useFlg = ?';
			$type_search .= 'i';
			$param_search[] = $useFlg;
		}
		 
		//分页
		if (!empty($page) && !empty($rp)){
			$str_limit = sprintf(' LIMIT %d, %d', ($page - 1) * $rp, $rp);
		}
		
		//排序
		if (!empty($sortname) && !empty($sortorder)){
			$str_order = sprintf(' ORDER BY %s %s', $sortname, $sortorder);
		}
		
		//组装SQL语句
		if (!empty($type_search)){
			$str_search = str_replace('WHERE AND', 'WHERE', $str_search);
			$sql_count = $sql_count.$str_search;
			$sql_search = $sql_search.$str_search.$str_group.$str_order.$str_limit;
		}else {
			$sql_search = $sql_search.$str_group.$str_order.$str_limit;
		}
		
		$value_count = empty($type_search) ? $this->dbca->stmt_query($sql_count) : $this->dbca->stmt_query($sql_count,$type_search,$param_search);
		
		if ($value_count){
		
			$return_data['code'] = 200;
			 
			//总记录条数
			$return_data['message']['total'] = $value_count[0]->countNum;
		
			//得到查询结果
			$return_data['message']['data'] = empty($type_search) ? $this->dbca->stmt_query($sql_search) : $this->dbca->stmt_query($sql_search,$type_search,$param_search);
			 
		}else {
			$return_data['code'] = 200;
			$return_data['message']['total'] = 0;
			$return_data['message']['data'] = '';
		}
		
		return $return_data;
	}
	
	/* 
	 * 新增、编辑营销活动
	 *  */
	public function editMarketingPorject ($importData){
		
		//错误信息
		$error = '';
		
		/* 传入数据有效性验证start */
		//没有传入数据
		if (empty($importData)) $error .= '没有传入任何数据<br/>';
		
		//operFlg：2，新增；3，修改
		if (!isset($importData['operFlg']) || !in_array($importData['operFlg'], array(2,3))){
			$error .= '传入operFlg错误<br/>';
		}
		
		if ($importData['operFlg'] == 2 && !isset($importData['creator'])) {
			$error .= '创建人不能为空<br/>';
		}
		
		if ($importData['operFlg'] == 3 && !isset($importData['editor'])) {
			$error .= '修改人不能为空<br/>';
		}
		
		if (!isset($importData['mainInfo']) || empty($importData['mainInfo'])) {
			$error .= '活动主信息不能为空<br/>';
		}
		
		if (!isset($importData['mainInfo']['projectName']) || empty($importData['mainInfo']['projectName'])) {
			$error .= '活动名称不能为空<br/>';
		}
		
		if (!isset($importData['mainInfo']['groupID']) || empty($importData['mainInfo']['groupID']) || !is_numeric($importData['mainInfo']['groupID'])) {
			$error .= '活动类型不能为空，且必须为数字<br/>';
		}
		
		if (!isset($importData['mainInfo']['useFlg']) || !in_array($importData['mainInfo']['useFlg'], array(0,1))) {
			$error .= '启用状态不能为空，且必须为数字<br/>';
		}
		
		if (!isset($importData['mainInfo']['startDate']) || empty($importData['mainInfo']['startDate'])) {
			$error .= '活动开始时间不能为空<br/>';
		}
		
		if (!isset($importData['mainInfo']['endDate']) || empty($importData['mainInfo']['endDate'])) {
			$error .= '活动结束时间不能为空<br/>';
		}
		
		if (!isset($importData['addInfo']) || empty($importData['addInfo'])) {
			$error .= '活动附加信息不能为空<br/>';
		}
		
		if (isset($importData['mainInfo']['groupID'])){
			switch ($importData['mainInfo']['groupID']){
				case 1:
					if (!isset($importData['addInfo'][0]['giftType']) || empty($importData['addInfo'][0]['giftType']) || !is_numeric($importData['addInfo'][0]['giftType'])) {
						$error .= '礼品发放方式传值错误<br/>';
					}
					if (!isset($importData['addInfo'][0]['goodsID']) || empty($importData['addInfo'][0]['goodsID'])) {
						$error .= '商品编号传值错误<br/>';
					}
					if (!isset($importData['addInfo'][0]['goodsName']) || !is_string($importData['addInfo'][0]['goodsName'])) {
						$error .= '商品名称传值错误<br/>';
					}
					if (($importData['addInfo'][0]['giftType'] != 1) && empty($importData['addInfo'][0]['goodsAmount']) || (!empty($importData['addInfo'][0]['goodsAmount']) && !is_numeric($importData['addInfo'][0]['goodsAmount']))) {
						$error .= '每日发放数量传值错误<br/>';
					}
					if ((!isset($importData['addInfo'][0]['oldPicName']) || empty($importData['addInfo'][0]['oldPicName'])) && (!isset($importData['addInfo'][0]['picName']) || empty($importData['addInfo'][0]['picName']))) {
						$error .= '商品图片不能为空<br/>';
					}
					break;
			}
		}
		
		if ($importData['operFlg'] == 3 && (!isset($importData['mainInfo']['projectID']) || empty($importData['mainInfo']['projectID']))) {
			$error .= '原活动ID传值错误<br/>';
		}
		
		if (!empty($error)){
			return array('code' => 400, 'message' => $error);
		}
		/* 传入数据有效性验证end */
		
		$operFlg = $importData['operFlg'];//operFlg
		$creator = $importData['creator'];//创建人
		$editor = $importData['editor'];//修改人
		$projectName = trim($importData['mainInfo']['projectName']);//活动名
		$projectID = trim($importData['mainInfo']['projectID']);//活动ID
		$groupID = trim($importData['mainInfo']['groupID']);//活动类型ID
		$useFlg = trim($importData['mainInfo']['useFlg']);//启用状态
		$startDate = trim($importData['mainInfo']['startDate']);//开始时间
		$endDate = trim($importData['mainInfo']['endDate']);//开始时间
		$participateTimes = trim($importData['mainInfo']['participateTimes']);//每人每天允许参与次数
		$addInfo =  $importData['addInfo'];
		
		/* 检测该时间段内是否已有该活动类型、且处于启用状态的活动start */
		
		$arg_arr = array(
				'groupID'		=> $groupID,
				'useFlg'		=> $useFlg,
				'startDate'		=> $startDate,
				'endDate'		=> $endDate,
				'projectID'		=> $projectID
				);
		$checkInfo = self::checkProject($arg_arr);
		if (!$checkInfo){
			$return_data['code'] = 399;
			$return_data['message'] = '该时间段内已有处于启用状态的该类型活动';
			return $return_data;
		}
		
		/* 检测该时间段内是否已有该活动类型、且处于启用状态的活动end */
		
		/*******检测商品是否存在、在售、有库存start********/
		//检测选购商品
		if (!empty($addInfo)){
			
			$goodsIDArr = array();
			
			foreach ($addInfo as $infoItem){
				$goods_obj = new entity('goods_list');
				
				$ruleID = trim($infoItem['ruleID']);
				$goodsID = trim($infoItem['goodsID']);
				
				$goods_obj->product_code = $goodsID;
				$goods_obj->useFlg = 1;
				$goods_obj->forsale = 1;
				if (!$this->dbca->fetch($goods_obj)){
					$return_data['code'] = 400;
					$return_data['message'] = '编号['.$goodsID.']商品不存在或已下架或没有库存';
					return $return_data;
				}
				
				$goodsIDArr[] = $ruleID.'-'.$goodsID;//有效的ruleID与商品ID组成的数组，在编辑时，进行数据库操作时用于比对
			}
		}
		/*******检测商品是否存在、在售、有库存end********/
		
		//返回的提示信息
		$message = ($operFlg == 2) ? '新增活动成功' : '修改活动成功';
		
		//保存到数据库
		try {
		
			$this->dbca->beginTransaction();
			
			//保存到project_detail中
			$detail_obj = new entity('project_detail');
			$detail_obj->projectID = $projectID;
			if ($this->dbca->fetch($detail_obj)){
				$detail_obj->editor = $editor;
			}else {
				//如果fetch，且operFlg==3，则弹出错误
				if ($operFlg == 3){
					throw new Exception('您的页面已过期，请刷新页面', -1000);
				}
				$detail_obj->creator = $creator;
				$detail_obj->useFlg = $useFlg;//新增时默认启用
			}
			$detail_obj->projectName = $projectName;
			$detail_obj->startDate = $startDate.' 00:00:00';
			$detail_obj->endDate = $endDate.' 23:59:59';
			$detail_obj->groupID = $groupID;
			$detail_obj->participateTimes = $participateTimes;
		
			$result_add = $this->dbca->save($detail_obj);
		
			if (!empty($result_add) && $operFlg == 2){
				$projectID = $this->dbca->insert_id;
			}
		
			if ($operFlg == 3){
				
				/* 编辑时先查project_rule表中对应ruleID的goodsID，是否在传入的addInfo对应的goodsID组成的数组中，如果不在则删除对应的
				 * 数据；然后根据是否可以fetch到ruleID来添加或修改每条数据
				 *  */
				
				$sql_search = 'SELECT ruleID, goodsID FROM project_rules WHERE projectID = ?';
				
				$result_search = $this->dbca->stmt_query($sql_search,'i',$projectID);
				
				if (empty($result_search)){
					throw new Exception('该活动未设置规则，请刷新页面', -1000);
				}
				
				if (!empty($result_search)){
					foreach ($result_search as $goodsIDList){
						if (!in_array($goodsIDList->ruleID.'-'.$goodsIDList->goodsID, $goodsIDArr)){
							$sql_del = 'DELETE FROM project_rules WHERE ruleID = ?';
							$this->dbca->stmt_query($sql_del, 'i', $goodsIDList->ruleID);//删除没有对应的
						}
					}
				}
			}
			
			//将传入的$addInfo保存进project_rules中
			if (!empty($addInfo)){
				foreach ($addInfo as $addInfo_item){
					$rule_obj = new entity('project_rules');
					
					$rule_obj->ruleID = $addInfo_item['ruleID']; 
					
					if ($this->dbca->fetch($rule_obj)){
						$rule_obj->editor = $editor;
					}else {
						$rule_obj->creator = $creator;
					}
					$thumbpic = empty($addInfo_item['picName']) ? trim($addInfo_item['oldPicName']) : trim($addInfo_item['picName']);//活动图片
					
					$rule_obj->projectID = $projectID;
					$rule_obj->goodsID = trim($addInfo_item['goodsID']);
					$rule_obj->goodsName = trim($addInfo_item['goodsName']);
					$rule_obj->goodsAmount = empty($addInfo_item['goodsAmount']) ? null : trim($addInfo_item['goodsAmount']);
					$rule_obj->goodsPic = '/quanliadmin/docroot/images/marketing/'.$thumbpic;
					if ($groupID == 1){
						$rule_obj->extend_2 = trim($addInfo_item['giftType']);	//注册有礼发放方式（1全部，2先来先得，3随机）
					}
					if ($groupID == 3){
						$rule_obj->extend_1 = trim($addInfo_item['assingAllNum']);	//总签到数
						$rule_obj->extend_2 = trim($addInfo_item['assingContiunNum']);	//连续签到数
					}
					if ($groupID == 2 || $groupID == 5 || $groupID == 6 || $groupID == 7){
						$rule_obj->extend_2 = trim($addInfo_item['awardChance']);	//中奖概率
						$rule_obj->extend_5 = trim($addInfo_item['awardName']);		//奖项名称
					}
					$this->dbca->save($rule_obj,'marketing');//新增或编辑
				}
			}
		
			$this->dbca->commit();
			
			$return_data = array('code'=>200, 'message'=>$message);
			return  $return_data;
		}catch (Exception $e){
			$this->dbca->rollBack();
			$error_msg = $e->getMessage();
			$return_data = array('code'=>500, 'message'=>$error_msg);
			return  $return_data;
		}
	}
	
	/* 
	 * 检测所选时间段内，所选活动类型是否存在已启用的该类型活动（保证指定时间段内，某活动类型的活动的唯一性）
	 * $importData = array(groupID, useFlg, startDate, endDate, projectID);
	 * return true/false
	 *  */
	public function checkProject ($importData){
		
		$groupID = !empty($importData['groupID']) ? trim($importData['groupID']) : null;
		$useFlg = !empty($importData['useFlg']) ? trim($importData['useFlg']) : null;
		$startDate = !empty($importData['startDate']) ? trim($importData['startDate']) : null;
		$endDate = !empty($importData['endDate']) ? trim($importData['endDate']) : null;
		$projectID = !empty($importData['projectID']) ? trim($importData['projectID']) : null;
		
		//如果为禁用状态则直接返回true
		if ($useFlg == null || $useFlg == 0 || $useFlg == ''){
			return true;
		}
				
		$sql_search = 'SELECT projectID FROM project_detail WHERE useFlg = 1 AND groupID = ? AND (
					    (startDate <= ? AND endDate >= ?) OR (startDate <= ? AND endDate >= ?) OR
						(startDate >= ? AND endDate <= ?) OR (startDate <= ? AND endDate >= ?)
					   )';
		$type = 'issssssss';
		$param = array(
				$groupID, 
				$startDate.' 00:00:00', 
				$startDate.' 23:59:59', 
				$endDate.' 00:00:00', 
				$endDate.' 23:59:59',
				$startDate.' 00:00:00',
				$endDate.' 23:59:59',
				$startDate.' 00:00:00',
				$endDate.' 23:59:59'
				);
		
		$result_search = $this->dbca->stmt_query($sql_search, $type, $param);
		
		if (empty($result_search)){//没有与新建活动有交集的直接返回true
			return true;
		}else {
			$count = count($result_search);
			if ($count == 1 && $result_search[0]->projectID == $projectID){//如果只有一个有交集，且找到的projectID与传入的相同（表示修改自身），则直接返回true
				return true;
			}else {
				return false;//其余情况都返回false
			}
		}	
	}
	
	/* 
	 * 查询当天的有效的活动
	 * $groupID //活动分组ID)
	 * return projectID/null
	 *  */
	public function getNowProject ($groupID){
		$today = date('Y-m-d');
		$sql_search = 'SELECT projectID FROM project_detail WHERE useFlg = 1 AND groupID = ? AND
					   (startDate <= ? AND endDate >= ?)';
		$type = 'iss';
		$param = array(
				$groupID,
				$today.' 00:00:00',
				$today.' 23:59:59'
		);
		
		$result_search = $this->dbca->stmt_query($sql_search, $type, $param);
		
		return $result_search;
	}
	
	/* 
	 * 查询一个营销活动的全部信息
	 *  */
	public function searProjectInfoAll ($importData){
		$projectID = isset($importData['projectID']) ? trim($importData['projectID']) : '';//活动ID
		$page = isset($importData['page']) ? trim($importData['page']) : '';//当前页
		$rp = isset($importData['rp']) ? trim($importData['rp']) : '';//每页记录数
		$sortname = isset($importData['sortname']) ? trim($importData['sortname']) : '';//排序字段名
		$sortorder = isset($importData['sortorder']) ? trim($importData['sortorder']) : '';//排序方式
        $useFlg= isset($importData['useFlg']) ? trim($importData['useFlg']) : null;//禁用启用标志
        $date = isset($importData['date']) ? trim($importData['date']) : '';//日期
        $groupID = isset($importData['groupID']) ? trim($importData['groupID']) : '';//活动分类ID

        //统计数目
        $sql_count = 'SELECT count(*) num FROM project_detail pd INNER JOIN project_rules pr ON pd.projectID = pr.projectID';

		
		$sql_search = 'SELECT pd.*, pr.ruleID, pr.goodsID, pr.goodsName, pr.goodsAmount, pr.goodsPic, pr.extend_1, 
					   pr.extend_2, pr.extend_3, pr.extend_4, pr.extend_5, pr.extend_6 FROM project_detail pd
					   INNER JOIN project_rules pr ON pd.projectID = pr.projectID';
		
		//排序
		$str_order = '';
		
		//分页
		$str_limit = '';
		
		//查询条件
		$str_search = ' WHERE';
		
		//查询参数类型
		$type_search = '';
		
		//查询参数数组
		$param_search = array();
		
		//查询条件：活动名
		if (!empty($projectID)){
			$str_search .= ' AND pd.projectID = ?';
			$type_search .= 's';
			$param_search[] = $projectID;
		}

        //查询条件：活动分类ID
        if (!empty($groupID)){
            $str_search .= ' AND pd.groupID = ?';
            $type_search .= 'i';
            $param_search[] = $groupID;
        }

        //查询条件：活动有效期
        if (!empty($date)){
            $str_search .= ' AND pd.startDate <= ? AND pd.endDate >= ?';
            $type_search .= 'ss';
            $param_search[] = $date.' 00:00:00';
            $param_search[] = $date.' 00:00:00';
        }

        //查询条件：启用状态
        if (!is_null($useFlg)){
            $str_search .= ' AND pd.useFlg = ?';
            $type_search .= 'i';
            $param_search[] = $useFlg;
        }
		
		//分页
		if (!empty($page) && !empty($rp)){
			$str_limit = sprintf(' LIMIT %d, %d', ($page - 1) * $rp, $rp);
		}
		
		//排序
		if (!empty($sortname) && !empty($sortorder)){
			$str_order = sprintf(' ORDER BY %s %s', $sortname, $sortorder);
		}
		
		//组装SQL语句
		if (!empty($type_search)){
			$str_search = str_replace('WHERE AND', 'WHERE', $str_search);
			$sql_search = $sql_search.$str_search.$str_order.$str_limit;
            $sql_count  = $sql_count.$str_search.$str_order;
		}else {
			$sql_search = $sql_search.$str_order.$str_limit;
            $sql_count  = $sql_count.$str_search.$str_order;
		}

        $return_count = empty($type_search) ? $this->dbca->stmt_query($sql_count) : $this->dbca->stmt_query($sql_count,$type_search,$param_search);
		$return_search = empty($type_search) ? $this->dbca->stmt_query($sql_search) : $this->dbca->stmt_query($sql_search,$type_search,$param_search);
		
		if (!empty($return_search)){
			return array('code'	=> 200, 'total'=>$return_count[0]->num,'message' => array('data'=>$return_search));
		}else {
			return array('code'	=> 400,'total'=>$return_count[0]->num, 'message' => '该活动不存在或已被删除');
		}
		
	}
	
	/* 删除活动
	 *  */
	public function deleteProject ($choiceIDArr){
		$error = '';
		
		if (empty($choiceIDArr)){
			$error = '请至少选择一条要删除的数据<br/>';
			return array('code' => 400, 'message' => $error);
		}
		
		try {
		
			$this->dbca->beginTransaction();
		
			foreach ($choiceIDArr as $projectID){
		
				if (!is_numeric($projectID)){
					throw new Exception('goodsChoiceID传值错误', -1000);
				}
		
				//检测promotion_selection中对应数据
				$detail_obj = new entity('project_detail');
		
				$detail_obj->projectID = $projectID;
		
				if (!$this->dbca->fetch($detail_obj)) {
					throw new Exception('活动号：'.$projectID.'的营销活动不存在或已被删除', -1000);
				}
		
				//删除promotion_selection表中对应数据
				$this->dbca->delete($detail_obj);
		
				//删除promotion_selection_detail中对应的数据
				$rules_obj = new entity('project_rules');
		
				$rules_obj->projectID = $projectID;
		
				if ($this->dbca->fetch($rules_obj)){
		
					//删除套装商品数据
					$sql_del = 'DELETE FROM project_rules WHERE projectID = ?';
					$this->dbca->stmt_query($sql_del,'i',$projectID);
				}
			}
		
			$this->dbca->commit();
		
			return array( 'code' => 200, 'message' => '删除成功' );
		
		}catch (Exception $e){
			$this->dbca->rollBack();
			$msg = $e->getMessage();
			return array( 'code' => 500, 'message' => $msg );
		}
	}
	
	/* 
	 * 参与抽奖
	 * $importData = array('projectID', 'pcustID');
	 * return array('code', 'message', 'data'=>array('ruleID', 'goodsID', 'goodsName', 'awardName'//奖项名称, 'goodsPic'));
	 *  */
	public function doChoujiang ($importData){
		
		$error_msg = '';
		
		if (!isset($importData['projectID']) || empty($importData['projectID']) || !is_numeric($importData['projectID'])){
			$error_msg .= '未传入正确的活动号<br/>';
		}
		
		if (!isset($importData['pcustID']) || empty($importData['pcustID']) || !is_numeric($importData['pcustID'])){
			$error_msg .= '未传入正确的客户号<br/>';
		}
		
		if (!empty($error_msg)){
			return array('code' => 400, 'message' => $error_msg);
		}
		$projectID = trim($importData['projectID']);
		$pcustID = trim($importData['pcustID']);
		
		$sql_searchRules = 'SELECT pr.*, pd.groupID FROM project_rules pr LEFT JOIN project_detail pd ON pr.projectID = pd.projectID WHERE pr.projectID = ?';
		$result_searchRules = $this->dbca->stmt_query($sql_searchRules, 'i', $projectID);
		
		if (empty($result_searchRules)){
			return array('code' => 401, 'message' => '该活动没有对应的抽奖规则');
		}
		
		/* 检测该用户当天是否已经参与抽奖start */
		
		$checkInfo = array('pcustID'=>$pcustID, 'projectID'=>$projectID, 'groupID'=>$result_searchRules[0]->groupID);
		
		$resule_checkParticipate = self::checkProjectHaveDone($checkInfo);
		
		if ($resule_checkParticipate['code'] != 200){
			if ($resule_checkParticipate['code'] == 201){
				return array('code'=>201, 'message'=>array('data'=>$resule_checkParticipate['data']));
			}else {
				return array('code'=>402, 'message'=>$resule_checkParticipate['message']);
			}
		}
		/* 检测该用户当天是否已经参与抽奖end */
		
		//抽奖抽到的幸运号码
		$luckNum = rand(0, 100);
		
		$luckArr = array(
				'ruleID'	=> '',
				'goodsID'	=> '',
				'goodsName'	=> '',
				'awardName'	=> '',
				'goodsPic'	=> '',
				'extend'	=> 100
				);
		
		//根据抽到的幸运号码去匹配中奖几率，小于该中奖几率则中了该奖项
		if (!empty($result_searchRules)){
			foreach ($result_searchRules as $rulesItem){
				if ($luckNum <= $rulesItem->extend_2 && $rulesItem->extend_2 <= $luckArr['extend']){
					$luckArr['ruleID'] = $rulesItem->ruleID;
					$luckArr['goodsID'] = $rulesItem->goodsID;
					$luckArr['goodsName'] = $rulesItem->goodsName;
					$luckArr['awardName'] = $rulesItem->extend_5;
					$luckArr['goodsPic'] = G_WEBSITE_DOMAINNAME.$rulesItem->goodsPic;
					$luckArr['extend'] = $rulesItem->extend_2;
				}
			}
		}
		
	try {
			$this->dbca->beginTransaction();
			
			$perday_obj = new entity('project_participate_perday');
			$perday_obj->pcustID = $pcustID;
			$perday_obj->projectID = $projectID;
			if ($this->dbca->fetch($perday_obj)){
				$perday_obj->editor = $pcustID;
				if (substr($perday_obj->createTime, 0, 10) == date('Y-m-d')){
					$perday_obj->participateTimes += 1;
				}else {
					$perday_obj->participateTimes = 1;
					$perday_obj->createTime = date('Y-m-d H:i:s');
				}
				$perday_obj->timeStamp = date('Y-m-d H:i:s');
				
			}else {
				$perday_obj->creator = $pcustID;
				$perday_obj->createTime = date('Y-m-d H:i:s');
				$perday_obj->participateTimes = 1;
			}
			$this->dbca->save($perday_obj,'marketing');
			
			//先保存参与活动次数、pcustID等信息到活动参与表(针对用户参与进行统计)
			$timesObj = new entity('project_times');
			$timesObj->pcustID = $pcustID;
			$timesObj->groupID = $result_searchRules[0]->groupID;
			$timesObj->projectID = $projectID;
			if ($this->dbca->fetch($timesObj)){
				$timesObj->editor = $pcustID;
			}else {
				$timesObj->creator = $pcustID;
			}
			$timesObj->participateTimes += 1;
			$this->dbca->save($timesObj,'analyse');
			
			//再保存到project_analyse_times表中（针对每个活动进行统计）
			$analyseObj = new entity('project_analyse_times');
			$analyseObj->projectID = $projectID;
			$analyseObj->createTime = date('Y-m-d');
			if ($this->dbca->fetch($analyseObj)){
				$analyseObj->editor = 'system';
				$analyseObj->participateTime += 1;//累加
				if (!empty($luckArr['ruleID'])){
					$analyseObj->getGiftTime += 1;//累加
				}
			}else {
				$analyseObj->creator = 'system';
				$analyseObj->participateTime = 1;//初始化为1
				if (!empty($luckArr['ruleID'])){
					$analyseObj->getGiftTime = 1;//初始化为1
				}
			}
			$analyseObj->groupID = $result_searchRules[0]->groupID;
			$this->dbca->save($analyseObj,'analyse');
			
			//如果中奖，则将中奖信息保存到活动客户表
			if (!empty($luckArr['ruleID'])){
				$customerObj = new entity('project_customer');
				$customerObj->pcustID = $pcustID;
				$customerObj->groupID = $result_searchRules[0]->groupID;
				$customerObj->projectID = $projectID;
				$customerObj->creator = $pcustID;
				$customerObj->ruleID = $luckArr['ruleID'];
				$customerObj->goodsID = $luckArr['goodsID'];
				$customerObj->succedFlg = 0;//此时奖品还未领取
				$customerObj->ruleName = $luckArr['awardName'];
				$customerObj->goodsName = $luckArr['goodsName'];
				$this->dbca->save($customerObj,'analyse');
			}
			
			$this->dbca->commit();
			
			//返回中奖信息
			return array( 'code' => 200, 'message' => array('data' => array($luckArr)) );
		
		}catch (Exception $e){
			$this->dbca->rollBack();
			$msg = $e->getMessage();
			error_log($msg);
			return array( 'code' => 500, 'message' => '系统错误' );
		}
	}
	
	/* 
	 * 领取礼品
	 * $importData = array('ruleID', 'pcustID', 'deliverID');
	 * return array('code', 'message');
	 *  */
	public function getGift ($importData){
		$error_msg = '';
		
		if (!isset($importData['pcustID']) || empty($importData['pcustID']) || !is_numeric($importData['pcustID'])){
			$error_msg .= '未传入正确的客户号<br/>';
		}
		
		if (!isset($importData['ruleID']) || empty($importData['ruleID']) || !is_numeric($importData['ruleID'])){
			$error_msg .= '未传入正确的ruleID<br/>';
		}
		
		if (!isset($importData['deliverID']) || empty($importData['deliverID']) || !is_numeric($importData['deliverID'])){
			$error_msg .= '未传入正确的deliverID<br/>';
		}
		
		if (!empty($error_msg)){
			return array('code' => 400, 'message' => $error_msg);
		}
		$pcustID = trim($importData['pcustID']);
		$ruleID = trim($importData['ruleID']);
		$deliverID = trim($importData['deliverID']);
		
		try {
		
			//先检测是否存在对应的pcustID、ruleID且succedFlg为0（表示尚未领取）的数据，如存在则更新相关信息到活动客户表
			$customerObj = new entity('project_customer');
			$customerObj->pcustID = $pcustID;
			$customerObj->ruleID = $ruleID;
			$customerObj->succedFlg = 0;
			if (!$this->dbca->fetch($customerObj)){
				return array('code'=>400, 'message'=>'未找到对应数据或已领取了礼品');
			}
			$customerObj->succedFlg = 1;//表示已完成
			$customerObj->deliverID = $deliverID;
			$this->dbca->save($customerObj,'analyse');
//			error_log('当前领取对象：'.print_r($customerObj,true));
			return array( 'code' => 200, 'message' => array('data'=>'领取完成'));
		
		}catch (Exception $e){
			$msg = $e->getMessage();
			error_log($msg);
			return array( 'code' => 500, 'message' => '系统错误' );
		}
	}
	
	/* 
	 * 参与注册有礼
	 * $importData = array('projectID', 'pcustID');
	 * return array('code', 'message', 'data'=>array('ruleID', 'goodsID', 'goodsName', 'goodsPic'));
	 *  */
	public function doRegist ($importData){
		$error_msg = '';
		
		if (!isset($importData['projectID']) || empty($importData['projectID']) || !is_numeric($importData['projectID'])){
			$error_msg .= '未传入正确的活动号<br/>';
		}
		
		if (!isset($importData['pcustID']) || empty($importData['pcustID']) || !is_numeric($importData['pcustID'])){
			$error_msg .= '未传入正确的客户号<br/>';
		}
		
		if (!empty($error_msg)){
			return array('code' => 400, 'message' => $error_msg);
		}
		$projectID = trim($importData['projectID']);
		$pcustID = trim($importData['pcustID']);
		
		$sql_searchRules = 'SELECT pr.*, pd.groupID FROM project_rules pr LEFT JOIN project_detail pd ON pr.projectID = pd.projectID WHERE pr.projectID = ? ';
		$result_searchRules = $this->dbca->stmt_query($sql_searchRules, 'i', $projectID);
		
		if (empty($result_searchRules)){
			return array('code' => 401, 'message' => '该活动没有对应的活动规则');
		}
		
		/* 检测该用户当天是否已经领取了免费礼品start */
		
		$checkInfo = array('pcustID'=>$pcustID, 'projectID'=>$projectID, 'groupID'=>$result_searchRules[0]->groupID);
		
		$resule_checkParticipate = self::checkProjectHaveDone($checkInfo);
		
		if ($resule_checkParticipate['code'] != 200){
			if ($resule_checkParticipate['code'] == 201){
				return array('code'=>201, 'message'=>array('data'=>$resule_checkParticipate['data']));
			}else {
				return array('code'=>402, 'message'=>$resule_checkParticipate['message']);
			}
		}
		/* 检测该用户当天是否已经领取了免费礼品end */
		
		$return_arr = array(
				'ruleID'		=> $result_searchRules[0]->ruleID,
				'goodsID'		=> $result_searchRules[0]->goodsID,
				'goodsName'		=> $result_searchRules[0]->goodsName,
				'goodsPic'		=> G_WEBSITE_DOMAINNAME.$result_searchRules[0]->goodsPic
		);
		
		try {
			$this->dbca->beginTransaction();
		
			$perday_obj = new entity('project_participate_perday');
			$perday_obj->pcustID = $pcustID;
			$perday_obj->projectID = $projectID;
			if ($this->dbca->fetch($perday_obj)){
				$perday_obj->editor = $pcustID;
				if (substr($perday_obj->createTime, 0, 10) == date('Y-m-d')){
					$perday_obj->participateTimes += 1;
				}else {
					$perday_obj->participateTimes = 1;
					$perday_obj->createTime = date('Y-m-d H:i:s');
				}
				$perday_obj->timeStamp = date('Y-m-d H:i:s');
			}else {
				$perday_obj->creator = $pcustID;
				$perday_obj->createTime = date('Y-m-d H:i:s');
				$perday_obj->participateTimes = 1;
			}
			$this->dbca->save($perday_obj,'marketing');
			
			//先检测用户是否已参与了该活动，如没有参与则保存数据到活动参与表
			$timesObj = new entity('project_times');
			$timesObj->pcustID = $pcustID;
			$timesObj->groupID = $result_searchRules[0]->groupID;
			$timesObj->projectID = $projectID;
			if ($this->dbca->fetch($timesObj)){
				return array('code'=>406, 'message'=>'该用户已领取了['.$result_searchRules[0]->projectID.']所对应的注册礼品 ');
			}
			$timesObj->creator = $pcustID;
			$timesObj->participateTimes += 1;
			$this->dbca->save($timesObj,'analyse');
			
			$getGifFlg = 0;
			$error = '';
		
			//extend_2=1表示全部发放；=2先来先得；=3随机抽取
			if ($result_searchRules[0]->extend_2 != 1 && $result_searchRules[0]->extend_1 >= $result_searchRules[0]->goodsAmount){
				$getGifFlg = 1;//该日发放礼品已全部发放
				$error = '该活动礼品已全部被领取';
			}
			
			if ($result_searchRules[0]->extend_2 == 3 && $getGifFlg == 0){
				//抽到的幸运号码
				$luckNum = rand(0, 100);
			
				//10%的抽取概率
				if ($luckNum <= 10){
					$getGifFlg = 2;//礼品发放方式为抽取时未能抽到礼品
					$error = '未抽取到注册有礼';
				}
			}
			
			//再保存到project_analyse_times表中（针对每个活动进行统计）
			$analyseObj = new entity('project_analyse_times');
			$analyseObj->projectID = $projectID;
			$analyseObj->createTime = date('Y-m-d');
			if ($this->dbca->fetch($analyseObj)){
				$analyseObj->editor = 'system';
				$analyseObj->participateTime += 1;//累加
				if ($getGifFlg == 0){
					$analyseObj->getGiftTime += 1;//累加
				}
			}else {
				$analyseObj->creator = 'system';
				$analyseObj->participateTime = 1;//初始化为1
				if ($getGifFlg == 0){
					$analyseObj->getGiftTime = 1;//初始化为1
				}
			}
			$analyseObj->groupID = $result_searchRules[0]->groupID;
			$this->dbca->save($analyseObj,'analyse');
			
			if ($getGifFlg == 0){
				//再保存相关信息到活动客户表
				$customerObj = new entity('project_customer');
				$customerObj->pcustID = $pcustID;
				$customerObj->groupID = $result_searchRules[0]->groupID;
				$customerObj->projectID = $result_searchRules[0]->projectID;
				$customerObj->creator = $pcustID;
				$customerObj->ruleID = $result_searchRules[0]->ruleID;
				$customerObj->goodsID = $result_searchRules[0]->goodsID;
				$customerObj->ruleName = '注册有礼';
				$customerObj->goodsName = $result_searchRules[0]->goodsName;
				$customerObj->succedFlg = 0;//0表示未完成
				$this->dbca->save($customerObj,'analyse');
				
				//修改活动规则表中对应的数据
				$ruleObj = new entity('project_rules');
				$ruleObj->ruleID = $result_searchRules[0]->ruleID;
				if (!$this->dbca->fetch($ruleObj)){
					return array('code'=>405, 'message'=>'该规则不存在 ' );
				}
				$ruleObj->extend_1 += 1;//已领取数量+1
				$this->dbca->save($ruleObj,'analyse');
			}
				
			$this->dbca->commit();
		
			if ($getGifFlg == 0){
				return array( 'code' => 200, 'message' => array('data' => array($return_arr)));
			}elseif ($getGifFlg == 1 || $getGifFlg == 2) {
				return array( 'code' => 202, 'message' => array('data' => array()) );
			}
			
		}catch (Exception $e){
			$this->dbca->rollBack();
			$msg = $e->getMessage();
			error_log($msg);
			return array( 'code' => 500, 'message' => '系统错误' );
		}
	}
	
	/*
	 * 参与签到有礼
	 * $importData = array('projectID', 'pcustID');
	 * return array('code', 'message', 'data'=>array('ruleID', 'goodsID', 'goodsName', 'goodsPic'));
	 *  */
	public function doAssign ($importData){
		$error_msg = '';
	
		if (!isset($importData['pcustID']) || empty($importData['pcustID']) || !is_numeric($importData['pcustID'])){
			$error_msg .= '未传入正确的客户号<br/>';
		}
		
		if (!isset($importData['projectID']) || empty($importData['projectID']) || !is_numeric($importData['projectID'])){
			$error_msg .= '未传入正确的projectID<br/>';
		}
				
		if (!empty($error_msg)){
			return array('code' => 400, 'message' => $error_msg);
		}
		$pcustID = trim($importData['pcustID']);
		$projectID = trim($importData['projectID']);
	
		$sql_searchRules = 'SELECT pr.*, pd.groupID FROM project_rules pr LEFT JOIN project_detail pd ON pr.projectID = pd.projectID WHERE pr.projectID = ? ';
		$result_searchRules = $this->dbca->stmt_query($sql_searchRules, 'i', $projectID);
	
		if (empty($result_searchRules)){
			return array('code' => 401, 'message' => '该活动没有对应的签到有礼规则');
		}
		
		/* 检测该用户当天是否已经领取了免费礼品start */
		
		$checkInfo = array('pcustID'=>$pcustID, 'projectID'=>$projectID, 'groupID'=>$result_searchRules[0]->groupID);
		
		$resule_checkParticipate = self::checkProjectHaveDone($checkInfo);
		
		if ($resule_checkParticipate['code'] != 200){
			if ($resule_checkParticipate['code'] == 201){
				return array('code'=>201, 'message'=>array('data'=>$resule_checkParticipate['data']));
			}else {
				return array('code'=>402, 'message'=>$resule_checkParticipate['message']);
			}
		}
		/* 检测该用户当天是否已经领取了免费礼品end */
		
		$sql_searchTimes = 'SELECT participateTimes, continueTimes FROM project_times WHERE projectID = ? AND pcustID = ?';
		$result_searchtimes = $this->dbca->stmt_query($sql_searchTimes, 'ii', array($projectID, $pcustID));
		$participateTimes = !empty($result_searchtimes) ? $result_searchtimes[0]->participateTimes : 0;//该会员参与该签到活动的总次数
		$continueTimes = !empty($result_searchtimes) ? $result_searchtimes[0]->continueTimes : 0;//该会员连续参与该签到活动的次数
		
		$rule_arr_ex1 = array(			//总签到数满足的规则数组
				'ruleID'		=> '',
				'goodsID'		=> '',
				'goodsAmount'	=> '',
				'goodsName'		=> '',
				'goodsPic'		=> '',
				'extend'		=> 0,
				'groupID'		=> ''
				);
		
		$rule_arr_ex2 = array(			//连续签到数满足的规则数组
				'ruleID'		=> '',
				'goodsID'		=> '',
				'goodsAmount'	=> '',
				'goodsName'		=> '',
				'goodsPic'		=> '',
				'extend'		=> 0,
				'groupID'		=> ''
				);
		
		/* 根据连续签到次数和总签到次数判断可以领取的礼品start */
		if (!empty($result_searchRules)){
			foreach ($result_searchRules as $item){
				//比较设定的总签到规则与该用户总签到数，获得该客户可获得的最高等礼品
				if ($item->extend_1 <= $participateTimes && $item->extend_1 >= $rule_arr_ex1['extend']){
					$rule_arr_ex1['ruleID'] = $item->ruleID;
					$rule_arr_ex1['goodsID'] = $item->goodsID;
					$rule_arr_ex1['goodsAmount'] = $item->goodsAmount;
					$rule_arr_ex1['goodsName'] = $item->goodsName;
					$rule_arr_ex1['goodsPic'] = G_WEBSITE_DOMAINNAME.$item->goodsPic;
					$rule_arr_ex1['extend'] = $item->extend_1;
					$rule_arr_ex1['groupID'] = $item->groupID;
				}
				
				//比较设定的连续签到规则与该用户连续签到数，获得该客户可获得的最高等礼品
				if ($item->extend_2 <= $continueTimes && $item->extend_2 >= $rule_arr_ex2['extend']){
					$rule_arr_ex2['ruleID'] = $item->ruleID;
					$rule_arr_ex2['goodsID'] = $item->goodsID;
					$rule_arr_ex2['goodsAmount'] = $item->goodsAmount;
					$rule_arr_ex2['goodsName'] = $item->goodsName;
					$rule_arr_ex2['goodsPic'] = G_WEBSITE_DOMAINNAME.$item->goodsPic;
					$rule_arr_ex2['extend'] = $item->extend_2;
					$rule_arr_ex2['groupID'] = $item->groupID;
				}
			}
		}
		
		//合并数组得到全部满足要求的规则数组
		$rule_arr = array($rule_arr_ex1, $rule_arr_ex2);
		/* 根据连续签到次数和总签到次数判断可以领取的礼品end */
		
		$return_arr = array();
		
		try {
			
			$this->dbca->beginTransaction();
			
			$perday_obj = new entity('project_participate_perday');
			$perday_obj->pcustID = $pcustID;
			$perday_obj->projectID = $projectID;
			if ($this->dbca->fetch($perday_obj)){
				$perday_obj->editor = $pcustID;
				if (substr($perday_obj->createTime, 0, 10) == date('Y-m-d')){
					$perday_obj->participateTimes += 1;
				}else {
					$perday_obj->participateTimes = 1;
					$perday_obj->createTime = date('Y-m-d H:i:s');
				}
				$perday_obj->timeStamp = date('Y-m-d H:i:s');
			}else {
				$perday_obj->creator = $pcustID;
				$perday_obj->createTime = date('Y-m-d H:i:s');
				$perday_obj->participateTimes = 1;
			}
			$this->dbca->save($perday_obj,'marketing');
			
			//先保存数据到活动参与表
			$timesObj = new entity('project_times');
			$timesObj->pcustID = $pcustID;
			$timesObj->groupID = $result_searchRules[0]->groupID;
			$timesObj->projectID = $projectID;
			if ($this->dbca->fetch($timesObj)){
				$timesObj->editor = $pcustID;
			}else {
				$timesObj->creator = $pcustID;
			}
			$timesObj->participateTimes += 1;//参与次数+1
			$timesObj->continueTimes += 1;//连续签到次数+1
			$this->dbca->save($timesObj,'analyse');
			
			//再保存到project_analyse_times表中（针对每个活动进行统计）
			$analyseObj = new entity('project_analyse_times');
			$analyseObj->projectID = $projectID;
			$analyseObj->createTime = date('Y-m-d');
			if ($this->dbca->fetch($analyseObj)){
				$analyseObj->editor = 'system';
				$analyseObj->participateTime += 1;//累加
				if (!empty($rule_arr_ex1['ruleID']) || !empty($rule_arr_ex2['ruleID'])){
					$analyseObj->getGiftTime += 1;//累加
				}
			}else {
				$analyseObj->creator = 'system';
				$analyseObj->participateTime = 1;//初始化为1
				if (!empty($rule_arr_ex1['ruleID']) || !empty($rule_arr_ex2['ruleID'])){
					$analyseObj->getGiftTime = 1;//初始化为1
				}
			}
			$analyseObj->groupID = $result_searchRules[0]->groupID;
			$this->dbca->save($analyseObj,'analyse');
			
			foreach ($rule_arr as $ruleItem){
				if ($ruleItem['extend'] && !empty($ruleItem['extend'])){
					//再判断该用户是否已领取了该规则对应的礼品，如没有则保存相关信息到活动客户表
					$customerObj = new entity('project_customer');
					$customerObj->pcustID = $pcustID;
					$customerObj->ruleID = $ruleItem['ruleID'];
					if (!$this->dbca->fetch($customerObj)){
						$customerObj->groupID = $ruleItem['groupID'];
						$customerObj->projectID = $projectID;
						$customerObj->creator = $pcustID;
						$customerObj->goodsID = $ruleItem['goodsID'];
						$customerObj->succedFlg = 0;//表示已领取
						if (!empty($rule_arr_ex1['ruleID'])){
							$customerObj->ruleName = '总签到次数：'.$ruleItem['extend'];
						}else {
							$customerObj->ruleName = '连续签到次数：'.$ruleItem['extend'];
						}
						$customerObj->goodsName = $ruleItem['goodsName'];
						$this->dbca->save($customerObj,'analyse');
						
						//将礼品数组返回
						$return_arr[] = array(
								'ruleID'	=> $ruleItem['ruleID'],
								'goodsID'	=> $ruleItem['goodsID'],
								'goodsName'	=> $ruleItem['goodsName'],
								'goodsPic'	=> G_WEBSITE_DOMAINNAME.$ruleItem['goodsPic']
								);
					}
				}	
			}
			
			$this->dbca->commit();
	
			return array( 'code' => 200, 'message' => array('data' => $return_arr)  );
	
		}catch (Exception $e){
			$this->dbca->rollBack();
			$msg = $e->getMessage();
			error_log($msg);
			return array( 'code' => 500, 'message' => '系统错误' );
		}
	}
	
	/*
	 * 参与免费有礼
	 * $importData = array('pcustID', 'projectID', 'ruleID');
	 * return array('code', 'message', 'data'=>array('ruleID', 'goodsID', 'goodsName', 'goodsPic'));
	 * code: 200完成参与；201当日已参与，但未完成领取；402当日已参与且已领取
	 *  */
	public function doFree ($importData){
		$error_msg = '';
	
		if (!isset($importData['pcustID']) || empty($importData['pcustID']) || !is_numeric($importData['pcustID'])){
			$error_msg .= '未传入正确的客户号<br/>';
		}
		
		if (!isset($importData['projectID']) || empty($importData['projectID']) || !is_numeric($importData['projectID'])){
			$error_msg .= '未传入正确的活动号<br/>';
		}
		
		if (!isset($importData['ruleID']) || empty($importData['ruleID']) || !is_numeric($importData['ruleID'])){
			$error_msg .= '未传入正确的规则号<br/>';
		}
	
		if (!empty($error_msg)){
			return array('code' => 400, 'message' => $error_msg);
		}
		$pcustID = trim($importData['pcustID']);
		$projectID = trim($importData['projectID']);
		$ruleID = trim($importData['ruleID']);
		
		$sql_searchRules = 'SELECT pr.*, pd.groupID FROM project_rules pr LEFT JOIN project_detail pd ON pr.projectID = pd.projectID WHERE pr.ruleID = ? ';
		$result_searchRules = $this->dbca->stmt_query($sql_searchRules, 'i', $ruleID);
		
		if (empty($result_searchRules)){
			return array('code' => 401, 'message' => '该活动没有对应的免费有礼规则');
		}
		
		/* 检测该用户当天是否已经领取了免费礼品start */
		
		$checkInfo = array('pcustID'=>$pcustID, 'projectID'=>$projectID, 'groupID'=>$result_searchRules[0]->groupID);
		
		$resule_checkParticipate = self::checkProjectHaveDone($checkInfo);
		
		if ($resule_checkParticipate['code'] != 200){
			if ($resule_checkParticipate['code'] == 201){
				return array('code'=>201, 'message'=>array('data'=>$resule_checkParticipate['data']));
			}else {
				return array('code'=>402, 'message'=>$resule_checkParticipate['message']);
			}
		}
		/* 检测该用户当天是否已经领取了免费礼品end */
		
		$giftFlg = 0;
	
		if ($result_searchRules[0]->extend_1 >= $result_searchRules[0]->goodsAmount){
			$giftFlg = 1;
		}
	
		$return_arr = array(
				'ruleID'		=> $ruleID,
				'goodsID'		=> $result_searchRules[0]->goodsID,
				'goodsName'		=> $result_searchRules[0]->goodsName,
				'goodsPic'		=> G_WEBSITE_DOMAINNAME.$result_searchRules[0]->goodsPic
		);
	
		try {
			$this->dbca->beginTransaction();
	
			$perday_obj = new entity('project_participate_perday');
			$perday_obj->pcustID = $pcustID;
			$perday_obj->projectID = $projectID;
			if ($this->dbca->fetch($perday_obj)){
				$perday_obj->editor = $pcustID;
				if (substr($perday_obj->createTime, 0, 10) == date('Y-m-d')){
					$perday_obj->participateTimes += 1;
				}else {
					$perday_obj->participateTimes = 1;
					$perday_obj->createTime = date('Y-m-d H:i:s');
				}
				$perday_obj->timeStamp = date('Y-m-d H:i:s');
			}else {
				$perday_obj->creator = $pcustID;
				$perday_obj->createTime = date('Y-m-d H:i:s');
				$perday_obj->participateTimes = 1;
			}
			$this->dbca->save($perday_obj,'marketing');
			
			//先保存数据到活动参与表
			$timesObj = new entity('project_times');
			$timesObj->pcustID = $pcustID;
			$timesObj->groupID = $result_searchRules[0]->groupID;
			$timesObj->projectID = $projectID;
			if ($this->dbca->fetch($timesObj)){
				$timesObj->editor = $pcustID;
			}else {
				$timesObj->creator = $pcustID;
			}
			$timesObj->participateTimes += 1;
			$this->dbca->save($timesObj,'analyse');
			
			//再保存到project_analyse_times表中（针对每个活动进行统计）
			$analyseObj = new entity('project_analyse_times');
			$analyseObj->projectID = $projectID;
			$analyseObj->createTime = date('Y-m-d');
			if ($this->dbca->fetch($analyseObj)){
				$analyseObj->editor = 'system';
				$analyseObj->participateTime += 1;//累加
				if ($giftFlg == 0){
					$analyseObj->getGiftTime += 1;//累加
				}
			}else {
				$analyseObj->creator = 'system';
				$analyseObj->participateTime = 1;//初始化为1
				if ($giftFlg == 0){
					$analyseObj->getGiftTime = 1;//初始化为1
				}
			}
			$analyseObj->groupID = $result_searchRules[0]->groupID;
			$this->dbca->save($analyseObj,'analyse');
	
			if ($giftFlg == 0){
				//再保存相关信息到活动客户表
				$customerObj = new entity('project_customer');
				$customerObj->pcustID = $pcustID;
				$customerObj->groupID = $result_searchRules[0]->groupID;
				$customerObj->projectID = $projectID;
				$customerObj->creator = $pcustID;
				$customerObj->ruleID = $ruleID;
				$customerObj->goodsID = $result_searchRules[0]->goodsID;
				$customerObj->succedFlg = 0;//1表示已领取
				$customerObj->ruleName = '免费送礼';
				$customerObj->goodsName = $result_searchRules[0]->goodsName;
				$this->dbca->save($customerObj,'analyse');
				
				//修改活动规则表中对应的数据
				$ruleObj = new entity('project_rules');
				$ruleObj->ruleID = $ruleID;
				if (!$this->dbca->fetch($ruleObj)){
					return array('code'=>405, 'message'=>'该规则不存在 ');
				}
				$ruleObj->extend_1 += 1;//已领取数量+1
				$this->dbca->save($ruleObj,'analyse');
			}
				
			$this->dbca->commit();
	
			if ($giftFlg == 0){
				return array( 'code' => 200, 'message' => array('data' => array($return_arr)) );
			}else{
				return array( 'code' => 403, 'message' => '该礼品已发完' );
			}
	
		}catch (Exception $e){
			$this->dbca->rollBack();
			$msg = $e->getMessage();
			error_log($msg);
			return array( 'code' => 500, 'message' => '系统错误' );
		}
	}
	
	/* 
	 * 检测当日是否已参加该活动，如已参加则检测是否已完成领取，未完成则提示已参与活动但未领取，已完成则直接提示已领取了商品
	 * $importData = array('projectID', 'pcustID', 'groupID')
	 * return array('code', 'data'(如尚未完成领取), 'message'（如已完成领取）)
	 * code： 200可以参与活动；201参与了活动但尚未完成领取；401参与并领取了礼品；400传值错误；402未抽取到礼品（注册抽取或抽奖）
	 *  */
	public function checkProjectHaveDone ($importData){
		$error_msg = '';
		
		if (!isset($importData['pcustID']) || empty($importData['pcustID']) || !is_numeric($importData['pcustID'])){
			$error_msg .= '未传入正确的客户号<br/>';
		}
		
		if (!isset($importData['projectID']) || empty($importData['projectID']) || !is_numeric($importData['projectID'])){
			$error_msg .= '未传入正确的活动号<br/>';
		}

		if (!isset($importData['groupID']) || empty($importData['groupID']) || !is_numeric($importData['groupID'])){
			$error_msg .= '未传入正确的活动类型ID<br/>';
		}
		
		if (!empty($error_msg)){
			return array('code' => 400, 'message' => $error_msg);
		}
		$pcustID = trim($importData['pcustID']);
		$projectID = trim($importData['projectID']);
		$groupID = trim($importData['groupID']);
		
		$sql_searchDetail = 'SELECT participateTimes FROM project_detail WHERE projectID = ?';//检测活动是否被删除，同时取得该活动允许参与最多次数
		
		$result_searchDetail = $this->dbca->stmt_query($sql_searchDetail, 'i', array($projectID));
		
		if (empty($result_searchDetail)){
			return array('code'=>403, 'message'=>'该活动不存在或已被删除');
		}
		$participateTimes = $result_searchDetail[0]->participateTimes;//每日每人允许最多参与次数
		
		//查询该客户参与该活动的次数和参与时间
		$sql_searchTimes = 'SELECT createTime, participateTimes FROM project_participate_perday WHERE pcustID = ? AND projectID = ?';
		
		$result_searchTimes = $this->dbca->stmt_query($sql_searchTimes, 'ii', array($pcustID, $projectID));
		
		//查询该客户参与活动的获奖信息
		$sql_searchSuccedFlg = 'SELECT pc.succedFlg, pc.ruleID, pr.goodsID, pr.goodsName, pr.extend_5, pr.goodsPic FROM project_customer pc LEFT JOIN project_rules pr ON pc.ruleID = pr.ruleID
								WHERE pc.projectID = ? AND pc.pcustID = ?';
		
		$result_succedFlg = $this->dbca->stmt_query($sql_searchSuccedFlg, 'ii', array($projectID, $pcustID));
		
		if (empty($result_searchTimes)){//project_participate_perday表中没有记录（尚未参与该活动）
			return array('code'=>200);
		}
		$createTime = substr($result_searchTimes[0]->createTime, 0, 10);
		$haveTimes = $result_searchTimes[0]->participateTimes;
		$today = date('Y-m-d');
		
		if ($createTime != $today || $haveTimes < $participateTimes){//没有当天参与活动的记录或是当天参与次数小于允许参与的最多次数
			return array('code'=>200);
		}
		
		$flg = '';
			
		if (!empty($result_succedFlg)){
			foreach ($result_succedFlg as $item){
				if ($item->succedFlg == 0){
					$return_arr[] = array(
							'ruleID'	=> $item->ruleID,
							'goodsID'	=> $item->goodsID,
							'goodsName'	=> $item->goodsName,
							'goodsPic'	=> G_WEBSITE_DOMAINNAME.$item->goodsPic,
							'awardName'	=> $item->extend_5
					);
				}else {
					$flg = 1;//表示有对应该活动的参与并完成领取的记录
				}
			}
		}
		
		if (!empty($return_arr)){
			return array('code'=>201, 'data'=>$return_arr);
		}elseif (empty($return_arr) && $flg == 1) {
			return array('code'=>401, 'message'=>'该礼品已完成领取');
		}else {
			return array('code'=>402, 'message'=>'您今天已参与该活动');//当天已参与活动但没有可领取的礼品
		}
	}
	
	
	
	
	
}